package org.example.http.demo;

import org.example.http.*;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/getCookie")
public class GetCookieServlet extends HttpServletImpl {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 添加cookie
        String name = request.getParameter("name");
        String value = request.getParameter("value");
        if( name!=null && value!=null){
            Cookie cookie = new CookieImpl(name, value);
            String path = request.getParameter("path");
            cookie.setPath(path);
            String maxAge = request.getParameter("maxAge");
            if( maxAge!=null){
                cookie.setMaxAge(Integer.parseInt(maxAge));
            }
            String domain = request.getParameter("domain");
            cookie.setDomain(domain);
            response.addCookie(cookie);
        }

        Cookie[] cookies = request.getCookies();
        String html = "";
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                html += "<li>" + cookie.getName() + " = " + cookie.getValue() + "</li>";
            }
            html = "<ul>" + html + "</ul>";
        }
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println(html);
    }
}
